package com.fangyi.yunmusic.controller;

import com.fangyi.yunmusic.config.UserTokenConfig;
import com.fangyi.yunmusic.exception.YunMusicException;
import com.fangyi.yunmusic.pojo.vo.UserVO;
import com.fangyi.yunmusic.service.UserService;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class LoginController {

    @Autowired
    private UserTokenConfig userTokenConfig;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Object login(String nickname, String password) throws Exception{
        //  1. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(nickname) || StringUtils.isBlank(password)) {
            throw new YunMusicException("用户名或密码不能为空...");
        }
        // 2. 判断用户是否存在
        UserVO userVO = userService.queryUserForLogin(nickname, password);
        if (userVO == null) {
            throw new YunMusicException("用户名或密码错误...");
        }
        // 3. 设置token
        // 刷新当前userId对应的token，以挤出其他地方登录的客户端
        String userToken = userTokenConfig.setUserToken(userVO.getId());
        userVO.setUserToken(userToken);

        return userVO;
    }

    @PostMapping("/logout")
    public Object logout(String userId) {
        userTokenConfig.removeUserToken(userId);
        return "注销成功";
    }

    @PostMapping("/checkToken")
    public Object checkToken() {
        return "OK";
    }
}
